// pages/water-power-quality/index.js
import config from "../../config/index";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    begin_work_year: "",
    workYearIsError: "",
    types: [], // 证书类型
  },

  handleWorkYearChange(event) {
    const value = event.detail;

    this.setData({
      workYearIsError: value ? "" : "请输入工作起始年",
    });
  },

  handleSumbit() {
    const { begin_work_year, types } = this.data;

    if (!begin_work_year) {
      this.setData({
        workYearIsError: "请输入工作起始年",
      });

      return;
    }

    const list = types.map((item) => {
      return {
        type: item.name,
        certificate_img: item.fileList.join(","),
      };
    });

    const param = { begin_work_year, sdgCertificateList: JSON.stringify(list) };

    wx.ajax
      .post("addOrEditUserSdgCertificate.action", param, true)
      .then((res) => {
        // console.log(res);
        if (res.success) {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });

          const timer = setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            });

            clearTimeout(timer);
          }, 1000);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
        }
      });
  },

  afterRead(event) {
    const image = event.detail.file;
    const id = event.target.dataset.id;

    const { types } = this.data;

    wx.ajax.uploadFile({
      filePath: image.url,
      callback: (url) => {
        if (url) {
          types.find((item) => item.id === id).fileList.push(url);
          types.find((item) => item.id === id).images.push(image);
          this.setData({
            types,
          });
        }
      },
    });
  },

  handleDelete(event) {
    const index = event.detail.index;
    const id = event.target.dataset.id;

    const { types } = this.data;

    types.find((item) => item.id === id).fileList.splice(index, 1);
    types.find((item) => item.id === id).images.splice(index, 1);

    this.setData({
      types,
    });
  },

  getData() {
    wx.ajax
      .post("findUserSdgCertificateByUserId.action", {}, true)
      .then((res) => {
        // console.log(res);
        if (res.success) {
          const result = res.result;

          this.setData({
            begin_work_year: result.user_info.begin_work_year,
          });

          if (
            result.userSdgCertifiCateList &&
            result.userSdgCertifiCateList.length
          ) {
            const timer = setTimeout(() => {
              const { types } = this.data;
              const list = result.userSdgCertifiCateList;

              types.forEach((item) => {
                const listItem = list.find((it) => it.type === item.name);
                const arr = listItem["certificate_img"].split(",");
                item.fileList = arr;
                item.images = arr.map((i) => {
                  return {
                    url: `${config.imageUrl}${i}`,
                  };
                });
              });

              this.setData({
                types,
              });

              clearTimeout(timer);
            }, 500);
          }
        }
      });
  },

  getTypes() {
    wx.ajax.post("querySdgCertificateType.action", {}, false).then((res) => {
      // console.log(res);
      if (res.success) {
        if (res.result && res.result.length) {
          this.setData({
            types: res.result.map((item) => {
              item.images = [];
              item.fileList = [];

              return item;
            }),
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData();
    this.getTypes();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
